package com.utils.conmponentbase.base.activity;

import android.app.Activity;
import android.content.Context;
import android.graphics.Rect;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;
import androidx.lifecycle.ViewModelProviders;

import com.alibaba.android.arouter.facade.Postcard;
import com.alibaba.android.arouter.launcher.ARouter;
import com.gyf.immersionbar.ImmersionBar;
import com.smarx.notchlib.NotchScreenManager;
import com.utils.conmponentbase.R;
import com.utils.conmponentbase.base.inner.IView;
import com.utils.conmponentbase.base.viewmodel.BaseViewModel;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * MvvmDemo com.utils.conmponentbase.base.activity
 * 2020-01-04 09:41
 */
public abstract class BaseActivity<Binding extends ViewDataBinding, VM extends BaseViewModel> extends AppCompatActivity implements IView {
    protected Activity mContext;
    protected ImmersionBar mImmersionBar;
    protected Binding mDataBinding;
    protected VM mViewModel;
    private String TAG = getClass().getSimpleName();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = this;
        //设置沉浸式状态栏
        setImmersionBar();
        initImmersionBar();

        //setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        //getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        if (null == mViewModel) {
            Class modelClass;
            Type type = getClass().getGenericSuperclass();
            if (type instanceof ParameterizedType) {
                modelClass = (Class) ((ParameterizedType) type).getActualTypeArguments()[2];
            } else {
                //如果没有指定泛型参数，则默认使用BaseViewModel
                modelClass = BaseViewModel.class;
            }
            mViewModel = (VM) createViewModel(this, modelClass);
        }
        if (getLayoutId() > 0) {
            mDataBinding = DataBindingUtil.setContentView(this, getLayoutId());
            mDataBinding.setLifecycleOwner(this);

            /*AndroidP以后的的设备 刘海屏/全面屏适配*/
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES;
                getWindow().setAttributes(lp);
                // 设置页面全屏显示
                final View decorView = getWindow().getDecorView();
                decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            } else {
                //
            }
            initEvent();
        }
        initData();
    }

    private void setImmersionBar() {
        mImmersionBar = ImmersionBar.with(this);
    }

    protected void initImmersionBar() {
        //沉浸式沉浸式状态栏
        mImmersionBar.statusBarColor(R.color.colorPrimary).fitsSystemWindows(true).init();
        //NotchTools.getFullScreenTools().fullScreenDontUseStatus(this);
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P) {
            NotchScreenManager.getInstance().setDisplayInNotch(this);
            NotchScreenManager.getInstance().getNotchInfo(this, notchScreenInfo -> {
                Log.i(TAG, "Is this screen notch? " + notchScreenInfo.hasNotch);
                if (notchScreenInfo.hasNotch) {
                    for (Rect rect : notchScreenInfo.notchRects) {
                        Log.i(TAG, "notch screen Rect =  " + rect.toShortString());
                    }
                }
            });
        }
    }

    @Override
    public abstract void initData();

    @Override
    public void initEvent() {

    }

    public VM getViewModel() {
        return mViewModel;
    }

    /**
     * 无参数传递跳转到Activity
     * 无跳转动画
     * 基于Arouter
     */
    public void gotoActivity(String path) {
        gotoActivity(path, false);
    }

    public void gotoActivity(String path, boolean isCloseCurrentActivity) {
        ARouter.getInstance().build(path).navigation();
        if (isCloseCurrentActivity) {
            mContext.finish();
        }
    }

    /**
     * 带参数传递跳转到Activity
     * 无跳转动画
     * 基于Arouter
     */
    public Postcard withValueActivity(String path) {
        return withValueActivity(path, false);
    }

    public Postcard withValueActivity(String path, boolean isCloseCurrentActivity) {
        Postcard aRouter = ARouter.getInstance().build(path);
        if (isCloseCurrentActivity) {
            mContext.finish();
        }
        return aRouter;
    }

    /**
     * 创建ViewModel
     *
     * @param cls activity
     * @param <T> ViewModel
     * @return ViewModel
     */
    public <T extends BaseViewModel> T createViewModel(AppCompatActivity activity, Class<T> cls) {
        return ViewModelProviders.of(activity).get(cls);
    }

    //==========================点击屏幕自动隐藏键盘================================//
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideKeyboard(v, ev)) {
                InputMethodManager imm =
                        (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(v.getWindowToken(),
                        InputMethodManager.HIDE_NOT_ALWAYS
                );
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    // Return whether touch the view.
    private boolean isShouldHideKeyboard(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] l = {0, 0};
            v.getLocationInWindow(l);
            int left = l[0],
                    top = l[1],
                    bottom = top + v.getHeight(),
                    right = left + v.getWidth();
            return !(event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom);
        }
        return false;
    }
    //==========================点击屏幕自动隐藏键盘================================//
}
